"""增强的答案生成节点"""

from typing import Dict, List, Any, Optional
from core.graph.chat_graph import ChatState, IntentType, ResearchStage


class AdvancedAnswerGenerator:
    """高级答案生成器"""
    
    def __init__(self):
        self.response_templates = {
            IntentType.QA: {
                "structure": ["introduction", "main_content", "examples", "references"],
                "tone": "informative"
            },
            IntentType.CODE_ANALYSIS: {
                "structure": ["overview", "detailed_analysis", "suggestions", "best_practices"],
                "tone": "technical"
            },
            IntentType.ERROR_DIAGNOSIS: {
                "structure": ["problem_identification", "root_cause", "solutions", "prevention"],
                "tone": "helpful"
            },
            IntentType.DEEP_RESEARCH: {
                "structure": ["executive_summary", "methodology", "findings", "conclusions", "recommendations"],
                "tone": "academic"
            },
            IntentType.CODE_GENERATION: {
                "structure": ["requirements", "implementation", "explanation", "usage"],
                "tone": "practical"
            },
            IntentType.TUTORIAL: {
                "structure": ["overview", "step_by_step", "examples", "exercises"],
                "tone": "educational"
            }
        }

    def format_knowledge_content(self, knowledge_items: List[Dict[str, Any]]) -> str:
        """格式化知识内容（支持外部工具结果）"""
        if not knowledge_items:
            return ""
        
        content_parts = []
        external_sources = []
        
        for item in knowledge_items[:5]:  # 增加到前5个
            content = item.get("content", "")
            metadata = item.get("metadata", {})
            source = metadata.get("source", item.get("source", ""))
            
            if content:
                # 区分内部和外部来源
                if metadata.get("type") == "external":
                    title = metadata.get("title", "")
                    url = metadata.get("url", "")
                    source_name = self._get_source_display_name(source)
                    
                    if title and url:
                        content_parts.append(f"• **[{source_name}]** {title}\n  {content[:200]}...")
                        external_sources.append(f"- [{title}]({url}) - {source_name}")
                    else:
                        content_parts.append(f"• **[{source_name}]** {content[:200]}...")
                else:
                    content_parts.append(f"• {content}")
        
        result = "\n\n".join(content_parts)
        
        # 添加外部来源链接
        if external_sources:
            result += "\n\n**🔗 外部参考链接**:\n" + "\n".join(external_sources)
        
        return result
    
    def _get_source_display_name(self, source: str) -> str:
        """获取来源显示名称"""
        source_names = {
            "cairo_docs": "Cairo 官方文档",
            "starknet_docs": "Starknet 官方文档", 
            "github_code": "GitHub 代码",
            "github_issues": "GitHub Issues",
            "stackoverflow": "Stack Overflow"
        }
        return source_names.get(source, source)

    def format_code_analysis(self, cairo_context: Dict[str, Any]) -> str:
        """格式化代码分析结果 - 增强版"""
        if not cairo_context.get("has_code"):
            return ""
        
        analysis_parts = []
        
        # 1. 基本信息
        code_type = cairo_context.get("code_type", "unknown")
        complexity = cairo_context.get("complexity_score", 0)
        complexity_level = "低" if complexity < 3 else "中" if complexity < 7 else "高"
        
        analysis_parts.append("# 🔍 Cairo 代码安全分析报告")
        analysis_parts.append("")
        analysis_parts.append("## 📊 基本信息")
        analysis_parts.append(f"• **代码类型**: {code_type}")
        analysis_parts.append(f"• **复杂度**: {complexity_level} ({complexity:.1f}/10)")
        
        # 依赖项
        dependencies = cairo_context.get("dependencies", [])
        if dependencies:
            deps_str = ", ".join(dependencies[:5])
            analysis_parts.append(f"• **依赖项**: {deps_str}")
        
        # 2. 安全评级
        security_rating = cairo_context.get("security_rating", {})
        if security_rating:
            rating = security_rating.get("rating", "未知")
            color = security_rating.get("color", "⚪")
            score = security_rating.get("score", 0)
            
            analysis_parts.append("")
            analysis_parts.append("## 🛡️ 安全评级")
            analysis_parts.append(f"### {color} **{rating}** (评分: {score}/100)")
            
            # 安全问题统计
            critical = security_rating.get("critical_issues", 0)
            high = security_rating.get("high_issues", 0)
            medium = security_rating.get("medium_issues", 0)
            low = security_rating.get("low_issues", 0)
            
            if critical + high + medium + low > 0:
                analysis_parts.append("")
                analysis_parts.append("**问题分布**:")
                if critical > 0:
                    analysis_parts.append(f"• 🚨 严重: {critical} 个")
                if high > 0:
                    analysis_parts.append(f"• 🔴 高危: {high} 个")
                if medium > 0:
                    analysis_parts.append(f"• 🟡 中等: {medium} 个")
                if low > 0:
                    analysis_parts.append(f"• 🟢 低危: {low} 个")
        
        # 3. 详细安全问题
        security_issues = cairo_context.get("security_issues", [])
        if security_issues:
            analysis_parts.append("")
            analysis_parts.append("## ⚠️ 安全漏洞详情")
            
            # 按严重程度排序
            severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
            sorted_issues = sorted(security_issues, key=lambda x: severity_order.get(x.get("severity", "info"), 4))
            
            for i, issue in enumerate(sorted_issues[:8], 1):  # 最多显示8个问题
                severity = issue.get("severity", "unknown")
                message = issue.get("message", "未知问题")
                description = issue.get("description", "")
                suggestion = issue.get("suggestion", "")
                cwe = issue.get("cwe", "")
                impact = issue.get("impact", "")
                
                analysis_parts.append(f"### {i}. {message}")
                if description:
                    analysis_parts.append(f"**问题描述**: {description}")
                if impact:
                    analysis_parts.append(f"**潜在影响**: {impact}")
                if suggestion:
                    analysis_parts.append(f"**修复建议**: {suggestion}")
                if cwe:
                    analysis_parts.append(f"**CWE编号**: {cwe}")
                analysis_parts.append("")
        
        # 4. 代码质量评估
        quality_metrics = cairo_context.get("quality_metrics", {})
        if quality_metrics:
            overall_score = quality_metrics.get("overall_score", 0)
            readability = quality_metrics.get("readability_score", 0)
            maintainability = quality_metrics.get("maintainability_score", 0)
            documentation = quality_metrics.get("documentation_score", 0)
            best_practices = quality_metrics.get("best_practices_score", 0)
            
            analysis_parts.append("## 📈 代码质量评估")
            analysis_parts.append(f"### 总体评分: {overall_score:.1f}/100")
            analysis_parts.append("")
            analysis_parts.append("**详细评分**:")
            analysis_parts.append(f"• 📖 可读性: {readability:.1f}/100")
            analysis_parts.append(f"• 🔧 可维护性: {maintainability:.1f}/100")
            analysis_parts.append(f"• 📚 文档完整性: {documentation:.1f}/100")
            analysis_parts.append(f"• ✅ 最佳实践: {best_practices:.1f}/100")
            
            # 改进建议
            recommendations = quality_metrics.get("recommendations", [])
            if recommendations:
                analysis_parts.append("")
                analysis_parts.append("**改进建议**:")
                for rec in recommendations[:5]:  # 最多显示5个建议
                    analysis_parts.append(f"• {rec}")
        
        # 5. 语法错误
        syntax_errors = cairo_context.get("syntax_errors", [])
        if syntax_errors:
            analysis_parts.append("")
            analysis_parts.append("## 🔧 语法问题")
            for i, error in enumerate(syntax_errors[:3], 1):  # 最多显示3个错误
                error_type = error.get("type", "unknown")
                message = error.get("message", "未知错误")
                severity = error.get("severity", "error")
                analysis_parts.append(f"{i}. **{severity.upper()}**: {message}")
        
        # 6. 总结和建议
        if security_issues or syntax_errors:
            analysis_parts.append("")
            analysis_parts.append("## 💡 总结建议")
            
            if any(issue.get("severity") == "critical" for issue in security_issues):
                analysis_parts.append("🚨 **立即修复**: 代码存在严重安全漏洞，建议立即修复后再部署")
            elif any(issue.get("severity") == "high" for issue in security_issues):
                analysis_parts.append("⚠️ **优先修复**: 代码存在高危安全问题，建议优先修复")
            elif security_issues:
                analysis_parts.append("✅ **建议优化**: 代码基本安全，建议按照修复建议进行优化")
            else:
                analysis_parts.append("✅ **代码安全**: 未发现明显安全问题")
        
        return "\n".join(analysis_parts)

    def format_error_diagnosis(self, error_diagnosis: Optional[Dict[str, Any]]) -> str:
        """格式化错误诊断结果"""
        if not error_diagnosis:
            return ""
        
        diagnosis_parts = []
        
        # 错误类型
        error_type = error_diagnosis.get("error_type", "unknown")
        confidence = error_diagnosis.get("confidence_score", 0)
        diagnosis_parts.append(f"**错误类型**: {error_type} (置信度: {confidence:.1%})")
        
        # 根本原因
        root_cause = error_diagnosis.get("root_cause", "")
        if root_cause:
            diagnosis_parts.append(f"**根本原因**: {root_cause}")
        
        # 修复建议
        fix_suggestions = error_diagnosis.get("fix_suggestions", [])
        if fix_suggestions:
            diagnosis_parts.append("**修复建议**:")
            for i, suggestion in enumerate(fix_suggestions[:2], 1):
                desc = suggestion.get("description", "")
                example = suggestion.get("code_example", "")
                diagnosis_parts.append(f"{i}. {desc}")
                if example:
                    diagnosis_parts.append(f"   ```cairo\n   {example}\n   ```")
        
        return "\n".join(diagnosis_parts)

    def format_research_report(self, research_context: Optional[Dict[str, Any]]) -> str:
        """格式化研究报告"""
        if not research_context:
            return ""
        
        final_report = research_context.get("final_report")
        if not final_report:
            # 如果没有最终报告，显示进度
            current_stage = research_context.get("current_stage", ResearchStage.INITIAL)
            questions = research_context.get("research_questions", [])
            
            report_parts = [
                f"**研究进度**: {current_stage.value}",
                "**研究问题**:"
            ]
            for i, question in enumerate(questions[:3], 1):
                report_parts.append(f"{i}. {question}")
            
            return "\n".join(report_parts)
        
        # 格式化最终报告
        report_parts = []
        
        title = final_report.get("title", "研究报告")
        report_parts.append(f"# {title}")
        
        summary = final_report.get("executive_summary", "")
        if summary:
            report_parts.append(f"## 执行摘要\n{summary}")
        
        findings = final_report.get("key_findings", [])
        if findings:
            report_parts.append("## 关键发现")
            for finding in findings:
                report_parts.append(f"• {finding}")
        
        conclusions = final_report.get("conclusions", [])
        if conclusions:
            report_parts.append("## 结论")
            for conclusion in conclusions:
                report_parts.append(f"• {conclusion}")
        
        recommendations = final_report.get("recommendations", [])
        if recommendations:
            report_parts.append("## 建议")
            for rec in recommendations:
                report_parts.append(f"• {rec}")
        
        confidence = final_report.get("confidence_score", 0)
        if confidence > 0:
            report_parts.append(f"## 置信度\n{confidence:.1%}")
        
        return "\n".join(report_parts)

    def generate_structured_response(self, state: ChatState) -> str:
        """生成结构化响应"""
        user_intent = state.get("user_intent", IntentType.OTHER)
        cairo_context = state.get("cairo_context", {})
        error_diagnosis = state.get("error_diagnosis")
        research_context = state.get("research_context")
        knowledge_items = state.get("retrieved_knowledge", [])
        
        response_parts = []
        
        # 根据意图生成不同的响应结构
        if user_intent == IntentType.ERROR_DIAGNOSIS and error_diagnosis:
            response_parts.append("# 🔍 错误诊断报告")
            response_parts.append(self.format_error_diagnosis(error_diagnosis))
            
        elif user_intent == IntentType.CODE_ANALYSIS and cairo_context.get("has_code"):
            response_parts.append("# 📊 代码分析报告")
            response_parts.append(self.format_code_analysis(cairo_context))
            
        elif user_intent == IntentType.DEEP_RESEARCH:
            response_parts.append(self.format_research_report(research_context))
            
        else:
            # 增强的通用知识问答格式
            response_parts.append("# 💡 Cairo 助手回答")
            
            # 评估知识库质量并决定回答策略
            has_quality_knowledge = self._evaluate_knowledge_quality(knowledge_items, 
                                                                   state["messages"][-1]["content"] if state["messages"] else "")
            
            if has_quality_knowledge:
                # 有高质量知识库内容时的处理
                response_parts.append("## 📖 核心概念")
                response_parts.append(self.format_knowledge_content(knowledge_items))
                
                # 添加实践建议
                practical_advice = self._generate_practical_advice(user_intent, knowledge_items)
                if practical_advice:
                    response_parts.append("## 💡 实践建议")
                    response_parts.append(practical_advice)
                
                # 添加相关概念
                related_concepts = self._generate_related_concepts(knowledge_items)
                if related_concepts:
                    response_parts.append("## 🔗 相关概念")
                    response_parts.append(related_concepts)
            else:
                # 知识库内容不足时，基于模型能力生成结构化回答
                response_parts.append("## 🧠 专业分析")
                fallback_content = self._generate_structured_fallback_content(user_intent, knowledge_items, state)
                response_parts.append(fallback_content)
                
                # 添加基于意图的通用建议
                general_advice = self._generate_intent_based_advice(user_intent)
                if general_advice:
                    response_parts.append("## 💡 通用建议")
                    response_parts.append(general_advice)
                
                # 添加进一步学习建议
                learning_suggestions = self._generate_learning_suggestions(user_intent)
                if learning_suggestions:
                    response_parts.append("## 📚 进一步学习")
                    response_parts.append(learning_suggestions)
            
            if cairo_context.get("has_code"):
                response_parts.append("## 📊 代码分析")
                response_parts.append(self.format_code_analysis(cairo_context))
                
                # 添加代码建议
                code_suggestions = self._generate_code_suggestions(cairo_context)
                if code_suggestions:
                    response_parts.append("## 🛠️ 代码建议")
                    response_parts.append(code_suggestions)
        
        # 添加参考信息
        if knowledge_items:
            response_parts.append("## 📚 参考资料")
            unique_sources = set()
            for item in knowledge_items[:3]:
                source = item.get("source", "")
                category = item.get("category", "")
                if source and source not in unique_sources:
                    unique_sources.add(source)
                    response_parts.append(f"• {category}: {source}")
        
        return "\n\n".join(response_parts)

    def _generate_practical_advice(self, user_intent: IntentType, knowledge_items: List[Dict[str, Any]]) -> str:
        """生成实践建议"""
        advice_templates = {
            IntentType.QA: [
                "在实际开发中，建议先理解基本概念再进行实践",
                "可以通过编写简单示例来加深理解",
                "注意查阅官方文档获取最新信息"
            ],
            IntentType.CODE_GENERATION: [
                "编写代码时要注意类型安全和错误处理",
                "建议使用Cairo的最佳实践和编码规范",
                "测试代码的边界情况和异常场景"
            ]
        }
        
        # 基于知识内容生成特定建议
        content_keywords = " ".join([item.get("content", "") for item in knowledge_items[:3]])
        
        advice_list = []
        if "felt252" in content_keywords:
            advice_list.append("• 使用felt252时要注意类型转换，避免隐式转换错误")
            advice_list.append("• 对于需要比较的场景，考虑使用具体的整数类型如u32、u64")
        
        if "合约" in content_keywords or "contract" in content_keywords:
            advice_list.append("• 合约开发时要特别注意权限控制和安全性")
            advice_list.append("• 建议使用事件记录重要的状态变化")
        
        if "错误" in content_keywords or "error" in content_keywords:
            advice_list.append("• 使用Result类型进行优雅的错误处理")
            advice_list.append("• 添加详细的错误信息便于调试")
        
        # 添加通用建议
        general_advice = advice_templates.get(user_intent, advice_templates[IntentType.QA])
        for advice in general_advice[:2]:
            advice_list.append(f"• {advice}")
        
        return "\n".join(advice_list) if advice_list else ""
    
    def _generate_related_concepts(self, knowledge_items: List[Dict[str, Any]]) -> str:
        """生成相关概念"""
        content_text = " ".join([item.get("content", "") for item in knowledge_items[:3]])
        
        concept_map = {
            "felt252": ["整数类型 (u32, u64, u128)", "类型转换", "有限域运算"],
            "合约": ["存储变量", "事件系统", "权限控制", "ABI接口"],
            "函数": ["参数传递", "返回值", "可见性修饰符", "trait实现"],
            "数组": ["Span类型", "索引访问", "迭代器", "内存管理"],
            "错误": ["Result类型", "panic宏", "断言", "调试技巧"]
        }
        
        related = []
        for keyword, concepts in concept_map.items():
            if keyword in content_text:
                related.extend([f"• **{concept}**" for concept in concepts[:3]])
        
        return "\n".join(related[:6]) if related else ""
    
    def _generate_code_suggestions(self, cairo_context: Dict[str, Any]) -> str:
        """生成代码建议"""
        suggestions = []
        
        code_type = cairo_context.get("code_type", "")
        complexity = cairo_context.get("complexity_score", 0)
        security_issues = cairo_context.get("security_issues", [])
        
        if code_type == "function":
            suggestions.append("• 考虑添加详细的文档注释说明函数用途")
            suggestions.append("• 验证输入参数的有效性")
        
        if code_type == "contract":
            suggestions.append("• 实现适当的权限检查机制")
            suggestions.append("• 为重要操作添加事件记录")
        
        if complexity > 5:
            suggestions.append("• 考虑将复杂逻辑拆分为更小的函数")
            suggestions.append("• 添加单元测试覆盖复杂场景")
        
        if security_issues:
            suggestions.append("• 注意代码中的安全问题，建议进行安全审计")
        
        # 通用建议
        suggestions.extend([
            "• 遵循Cairo编码规范和最佳实践",
            "• 使用适当的错误处理机制"
        ])
        
        return "\n".join(suggestions[:5])

    def generate_simple_response(self, state: ChatState) -> str:
        """生成简单响应 - 增强版，支持智能fallback"""
        user_intent = state.get("user_intent", IntentType.OTHER)
        cairo_context = state.get("cairo_context", {})
        knowledge_items = state.get("retrieved_knowledge", [])
        user_text = state["messages"][-1]["content"] if state["messages"] else ""
        
        # 评估知识库结果质量
        has_quality_knowledge = self._evaluate_knowledge_quality(knowledge_items, user_text)
        
        if has_quality_knowledge:
            # 有高质量知识库内容时，基于知识库回答
            main_content = knowledge_items[0].get("content", "")
            return f"根据 Cairo 知识库：{main_content}"
        else:
            # 知识库内容不足时，启用智能fallback
            return self._generate_fallback_response(user_intent, cairo_context, user_text, knowledge_items)
    
    def _evaluate_knowledge_quality(self, knowledge_items: List[Dict[str, Any]], user_text: str) -> bool:
        """评估知识库结果质量 - 智能评估版"""
        if not knowledge_items:
            return False
        
        top_item = knowledge_items[0]
        top_score = top_item.get("relevance_score", 0)
        top_content = top_item.get("content", "")
        
        # 进一步降低相关性分数阈值，更宽松的标准
        if top_score < 0.05:  # 从0.1降到0.05
            return False
        
        # 更宽松的内容长度要求
        if len(top_content.strip()) < 5:  # 从10降到5
            return False
        
        user_text_lower = user_text.lower()
        content_lower = top_content.lower()
        
        # 智能意图识别
        code_generation_keywords = ["写", "生成", "创建", "实现", "合约", "代码", "函数", "示例", "例子", "模板"]
        question_keywords = ["什么", "如何", "怎么", "为什么", "是什么", "怎样", "?", "？"]
        analysis_keywords = ["分析", "检查", "审查", "评估", "优化", "改进"]
        
        is_code_request = any(keyword in user_text_lower for keyword in code_generation_keywords)
        is_question = any(keyword in user_text_lower for keyword in question_keywords)
        is_analysis = any(keyword in user_text_lower for keyword in analysis_keywords)
        
        # 对于代码生成请求，优先检查代码内容
        if is_code_request:
            # 检查是否包含代码块或代码片段
            code_indicators = ["```", "#[", "fn ", "struct ", "mod ", "impl ", "use ", "let ", "const ", "trait "]
            if any(indicator in content_lower for indicator in code_indicators):
                return True
            
            # 检查技术术语相关性
            tech_terms = ["erc20", "token", "contract", "cairo", "starknet", "felt", "storage", "mapping", "event", "function"]
            tech_match_count = sum(1 for term in tech_terms if term in content_lower)
            if tech_match_count >= 1:  # 至少匹配一个技术术语
                return True
        
        # 对于问答类请求，检查概念解释
        if is_question:
            explanation_indicators = ["是", "指", "表示", "用于", "可以", "能够", "定义", "概念", "原理"]
            if any(indicator in content_lower for indicator in explanation_indicators):
                return True
        
        # 对于分析类请求，检查分析内容
        if is_analysis:
            analysis_indicators = ["问题", "错误", "建议", "优化", "改进", "注意", "风险", "安全"]
            if any(indicator in content_lower for indicator in analysis_indicators):
                return True
        
        # 语义相似性检查（简化版）
        user_keywords = set(user_text_lower.split())
        content_keywords = set(content_lower.split())
        
        # 移除常见停用词
        stop_words = {"的", "是", "在", "有", "和", "或", "但", "如果", "那么", "这", "那", "一个", "一些", "什么", "如何", "怎么"}
        user_keywords = user_keywords - stop_words
        content_keywords = content_keywords - stop_words
        
        if not user_keywords:  # 如果用户关键词为空，采用宽松策略
            return len(content_lower) > 20  # 内容足够长就认为有价值
        
        overlap = len(user_keywords.intersection(content_keywords))
        overlap_ratio = overlap / len(user_keywords) if user_keywords else 0
        
        # 动态阈值：根据查询复杂度调整
        if len(user_keywords) <= 2:
            return overlap >= 1 or overlap_ratio >= 0.3  # 简单查询
        elif len(user_keywords) <= 5:
            return overlap >= 1 or overlap_ratio >= 0.2  # 中等查询
        else:
            return overlap >= 2 or overlap_ratio >= 0.15  # 复杂查询
        
        # 如果以上都不满足，但相关性分数较高，也认为有质量
        return top_score >= 0.15
    
    def _generate_fallback_response(self, user_intent: IntentType, cairo_context: Dict[str, Any], 
                                  user_text: str, knowledge_items: List[Dict[str, Any]]) -> str:
        """生成智能fallback响应，充分利用模型专业能力"""
        
        # 分析用户查询的核心需求
        core_need = self._extract_core_need(user_text, user_intent)
        
        # 构建专业的回答框架
        response_parts = []
        
        # 1. 专业开场，建立信任
        professional_intro = self._generate_professional_intro(user_intent, core_need)
        response_parts.append(professional_intro)
        
        # 2. 核心内容生成
        core_content = self._generate_core_content(user_intent, user_text, cairo_context, knowledge_items)
        response_parts.append(core_content)
        
        # 3. 实用建议和最佳实践
        practical_advice = self._generate_practical_guidance(user_intent, user_text)
        if practical_advice:
            response_parts.append("\n\n## 💡 实用建议\n")
            response_parts.append(practical_advice)
        
        # 4. 相关资源和进一步学习
        learning_resources = self._generate_learning_resources(user_intent, core_need)
        if learning_resources:
            response_parts.append("\n\n## 📚 进一步学习\n")
            response_parts.append(learning_resources)
        
        # 5. 专业免责声明（简化版）
        disclaimer = self._generate_smart_disclaimer(user_intent)
        if disclaimer:
            response_parts.append(f"\n\n---\n*{disclaimer}*")
        
        return "".join(response_parts)
    
    def _extract_core_need(self, user_text: str, user_intent: IntentType) -> str:
        """提取用户查询的核心需求"""
        user_text_lower = user_text.lower()
        
        # 技术关键词提取
        tech_keywords = []
        cairo_concepts = ["erc20", "token", "contract", "starknet", "felt", "storage", "mapping", "event", "function", "struct", "trait", "impl"]
        for concept in cairo_concepts:
            if concept in user_text_lower:
                tech_keywords.append(concept)
        
        # 操作关键词提取
        action_keywords = []
        actions = ["创建", "生成", "写", "实现", "分析", "优化", "修复", "解释", "学习"]
        for action in actions:
            if action in user_text_lower:
                action_keywords.append(action)
        
        # 构建核心需求描述
        if tech_keywords and action_keywords:
            return f"{action_keywords[0]} {tech_keywords[0]}"
        elif tech_keywords:
            return tech_keywords[0]
        elif action_keywords:
            return action_keywords[0]
        else:
            return "Cairo 开发"
    
    def _generate_professional_intro(self, user_intent: IntentType, core_need: str) -> str:
        """生成专业的开场白"""
        intros = {
            IntentType.QA: f"关于 {core_need}，让我基于 Cairo 语言的核心原理为您详细解答：",
            IntentType.CODE_ANALYSIS: f"我将运用 Cairo 编程的最佳实践来分析您的 {core_need}：",
            IntentType.ERROR_DIAGNOSIS: f"基于 Cairo 常见问题模式，我来帮您诊断 {core_need} 相关的问题：",
            IntentType.CODE_GENERATION: f"我将为您提供 {core_need} 的完整实现方案：",
            IntentType.TUTORIAL: f"让我为您提供 {core_need} 的系统性学习指导：",
            IntentType.OPTIMIZATION: f"我来为您的 {core_need} 提供优化建议：",
        }
        
        return intros.get(user_intent, f"基于我对 Cairo 生态的深入理解，我来为您解答 {core_need} 相关的问题：")
    
    def _generate_core_content(self, user_intent: IntentType, user_text: str, 
                             cairo_context: Dict[str, Any], knowledge_items: List[Dict[str, Any]]) -> str:
        """生成核心内容"""
        content_parts = []
        
        # 如果有部分知识库内容，先利用它们
        if knowledge_items:
            relevant_content = self._extract_relevant_snippets(knowledge_items, user_text)
            if relevant_content:
                content_parts.append("\n\n## 📖 相关概念\n")
                content_parts.append(relevant_content)
        
        # 基于意图生成专业内容
        if user_intent == IntentType.CODE_GENERATION:
            code_content = self._generate_code_template(user_text, cairo_context)
            content_parts.append("\n\n## 💻 代码实现\n")
            content_parts.append(code_content)
            
        elif user_intent == IntentType.CODE_ANALYSIS:
            if cairo_context.get("has_code"):
                analysis_content = self._generate_code_analysis_content(cairo_context)
                content_parts.append("\n\n## 🔍 代码分析\n")
                content_parts.append(analysis_content)
            else:
                content_parts.append("\n\n## 📝 分析指导\n")
                content_parts.append("要进行有效的代码分析，请提供具体的代码片段。我可以帮您检查：\n")
                content_parts.append("• **语法正确性**：Cairo 语法规范遵循情况\n")
                content_parts.append("• **类型安全**：变量类型使用是否合理\n")
                content_parts.append("• **性能优化**：是否遵循 Cairo 性能最佳实践\n")
                content_parts.append("• **安全性**：潜在的安全风险和漏洞")
                
        elif user_intent == IntentType.ERROR_DIAGNOSIS:
            error_content = self._generate_error_diagnosis_content(user_text, cairo_context)
            content_parts.append("\n\n## 🔧 问题诊断\n")
            content_parts.append(error_content)
            
        else:  # QA, TUTORIAL, etc.
            explanation_content = self._generate_explanation_content(user_text)
            content_parts.append("\n\n## 📚 详细解释\n")
            content_parts.append(explanation_content)
        
        return "".join(content_parts)
    
    def _extract_relevant_snippets(self, knowledge_items: List[Dict[str, Any]], user_text: str) -> str:
        """从知识库项目中提取相关片段"""
        snippets = []
        for item in knowledge_items[:2]:  # 最多使用前2个结果
            content = item.get("content", "")
            if len(content) > 50:  # 只使用有意义的内容
                # 截取前200字符作为摘要
                snippet = content[:200] + "..." if len(content) > 200 else content
                snippets.append(f"• {snippet}")
        
        return "\n".join(snippets) if snippets else ""
    
    def _generate_code_template(self, user_text: str, cairo_context: Dict[str, Any]) -> str:
        """生成代码模板"""
        user_text_lower = user_text.lower()
        
        if "erc20" in user_text_lower or "token" in user_text_lower:
            return """```cairo
#[starknet::contract]
mod ERC20Token {
    use starknet::ContractAddress;
    use starknet::get_caller_address;
    
    #[storage]
    struct Storage {
        name: felt252,
        symbol: felt252,
        decimals: u8,
        total_supply: u256,
        balances: LegacyMap<ContractAddress, u256>,
        allowances: LegacyMap<(ContractAddress, ContractAddress), u256>,
    }
    
    #[constructor]
    fn constructor(
        ref self: ContractState,
        name: felt252,
        symbol: felt252,
        decimals: u8,
        initial_supply: u256,
        recipient: ContractAddress
    ) {
        self.name.write(name);
        self.symbol.write(symbol);
        self.decimals.write(decimals);
        self.total_supply.write(initial_supply);
        self.balances.write(recipient, initial_supply);
    }
    
    #[external(v0)]
    fn transfer(ref self: ContractState, to: ContractAddress, amount: u256) -> bool {
        let caller = get_caller_address();
        self._transfer(caller, to, amount);
        true
    }
    
    #[generate_trait]
    impl InternalImpl of InternalTrait {
        fn _transfer(
            ref self: ContractState,
            from: ContractAddress,
            to: ContractAddress,
            amount: u256
        ) {
            let from_balance = self.balances.read(from);
            assert(from_balance >= amount, 'Insufficient balance');
            
            self.balances.write(from, from_balance - amount);
            let to_balance = self.balances.read(to);
            self.balances.write(to, to_balance + amount);
        }
    }
}
```

这是一个基础的 ERC20 代币合约模板，包含了核心功能：
• **存储结构**：定义代币的基本属性和状态
• **构造函数**：初始化代币参数
• **转账功能**：实现代币转移逻辑
• **内部函数**：封装通用的转账逻辑"""
        
        elif "function" in user_text_lower or "函数" in user_text_lower:
            return """```cairo
// 基础函数示例
fn calculate_fee(amount: u256, fee_rate: u256) -> u256 {
    amount * fee_rate / 10000  // 假设费率以基点表示
}

// 带错误处理的函数
fn safe_divide(a: u256, b: u256) -> Result<u256, felt252> {
    if b == 0 {
        Result::Err('Division by zero')
    } else {
        Result::Ok(a / b)
    }
}

// 结构体操作函数
#[derive(Drop, Serde)]
struct UserInfo {
    address: ContractAddress,
    balance: u256,
    last_update: u64,
}

fn update_user_balance(ref user: UserInfo, new_balance: u256) {
    user.balance = new_balance;
    user.last_update = starknet::get_block_timestamp();
}
```

函数设计的关键要点：
• **类型安全**：明确指定参数和返回值类型
• **错误处理**：使用 Result 类型处理可能的错误
• **引用传递**：使用 ref 关键字进行可变引用"""
        
        else:
            return """```cairo
// Cairo 基础代码结构示例
use starknet::ContractAddress;

#[derive(Drop, Serde)]
struct ExampleStruct {
    value: u256,
    owner: ContractAddress,
}

fn example_function(input: u256) -> u256 {
    // 实现您的逻辑
    input * 2
}

#[starknet::contract]
mod ExampleContract {
    #[storage]
    struct Storage {
        value: u256,
    }
    
    #[external(v0)]
    fn set_value(ref self: ContractState, new_value: u256) {
        self.value.write(new_value);
    }
    
    #[external(v0)]
    fn get_value(self: @ContractState) -> u256 {
        self.value.read()
    }
}
```

这个模板展示了 Cairo 的基本语法结构，您可以根据具体需求进行修改。"""
    
    def _generate_practical_guidance(self, user_intent: IntentType, user_text: str) -> str:
        """生成实用指导"""
        guidance_map = {
            IntentType.CODE_GENERATION: """• **测试先行**：编写代码前先设计测试用例
• **模块化设计**：将复杂功能拆分为小的、可重用的函数
• **错误处理**：使用 Result 类型处理可能的错误情况
• **文档注释**：为公共接口添加清晰的文档说明
• **安全检查**：特别注意整数溢出和权限控制""",
            
            IntentType.CODE_ANALYSIS: """• **静态分析**：使用 Cairo 编译器检查语法错误
• **代码审查**：关注逻辑漏洞和安全问题
• **性能评估**：分析 gas 消耗和执行效率
• **最佳实践**：对照 Cairo 编程规范检查代码风格
• **测试覆盖**：确保关键路径都有测试覆盖""",
            
            IntentType.ERROR_DIAGNOSIS: """• **错误分类**：区分编译时错误和运行时错误
• **日志分析**：仔细阅读错误信息和堆栈跟踪
• **逐步调试**：使用二分法定位问题代码段
• **环境检查**：确认 Cairo 版本和依赖库版本
• **社区求助**：在 StarkNet 社区寻求帮助""",
        }
        
        return guidance_map.get(user_intent, """• **持续学习**：关注 Cairo 和 StarkNet 的最新发展
• **实践项目**：通过实际项目加深理解
• **社区参与**：积极参与开源项目和技术讨论
• **文档阅读**：定期查阅官方文档和最佳实践指南""")
    
    def _generate_learning_resources(self, user_intent: IntentType, core_need: str) -> str:
        """生成学习资源建议"""
        return f"""• **官方文档**：Cairo Book 和 StarkNet 文档
• **示例代码**：GitHub 上的 Cairo 项目和合约示例
• **开发工具**：Scarb、Starkli 等 Cairo 开发工具链
• **测试框架**：学习使用 Cairo 测试框架进行单元测试
• **社区资源**：StarkNet 官方论坛和 Discord 社区"""
    
    def _generate_smart_disclaimer(self, user_intent: IntentType) -> str:
        """生成智能免责声明"""
        if user_intent == IntentType.CODE_GENERATION:
            return "代码示例仅供参考，实际使用前请进行充分测试和安全审计"
        elif user_intent == IntentType.ERROR_DIAGNOSIS:
            return "诊断建议基于常见问题模式，具体情况请结合完整代码上下文分析"
        else:
             return "建议结合官方文档验证相关信息的准确性"
    
    def _generate_code_analysis_content(self, cairo_context: Dict[str, Any]) -> str:
        """生成代码分析内容"""
        analysis_parts = []
        
        code_type = cairo_context.get("code_type", "代码")
        complexity_score = cairo_context.get("complexity_score", 0)
        
        analysis_parts.append(f"**代码类型**：{code_type}")
        
        if complexity_score > 0:
            analysis_parts.append(f"**复杂度评分**：{complexity_score:.1f}/10")
            
            if complexity_score < 3:
                analysis_parts.append("• 代码结构简单，易于理解和维护")
            elif complexity_score < 7:
                analysis_parts.append("• 代码复杂度适中，建议适当优化")
            else:
                analysis_parts.append("• 代码复杂度较高，建议重构以提高可维护性")
        
        # 检查是否有语法错误
        syntax_errors = cairo_context.get("syntax_errors", [])
        if syntax_errors:
            analysis_parts.append("\n**语法问题**：")
            for error in syntax_errors[:3]:  # 最多显示3个错误
                error_msg = error.get("message", "未知错误")
                analysis_parts.append(f"• {error_msg}")
        
        # 检查安全问题
        security_issues = cairo_context.get("security_issues", [])
        if security_issues:
            analysis_parts.append("\n**安全建议**：")
            for issue in security_issues[:3]:  # 最多显示3个问题
                issue_msg = issue.get("message", "未知安全问题")
                analysis_parts.append(f"• {issue_msg}")
        
        if not syntax_errors and not security_issues:
            analysis_parts.append("\n**总体评估**：代码结构良好，未发现明显问题")
        
        return "\n".join(analysis_parts)
    
    def _generate_error_diagnosis_content(self, user_text: str, cairo_context: Dict[str, Any]) -> str:
        """生成错误诊断内容"""
        user_text_lower = user_text.lower()
        diagnosis_parts = []
        
        # 常见错误模式识别
        if "编译" in user_text_lower or "compile" in user_text_lower:
            diagnosis_parts.append("**编译错误诊断**：")
            diagnosis_parts.append("• 检查语法是否正确，特别是括号、分号的匹配")
            diagnosis_parts.append("• 确认所有使用的类型和函数都已正确导入")
            diagnosis_parts.append("• 验证 Cairo 版本兼容性")
            
        elif "类型" in user_text_lower or "type" in user_text_lower:
            diagnosis_parts.append("**类型错误诊断**：")
            diagnosis_parts.append("• 检查变量类型声明是否正确")
            diagnosis_parts.append("• 确认函数参数和返回值类型匹配")
            diagnosis_parts.append("• 注意 felt252 和 u256 等类型的正确使用")
            
        elif "内存" in user_text_lower or "memory" in user_text_lower:
            diagnosis_parts.append("**内存相关问题**：")
            diagnosis_parts.append("• 检查是否正确使用了 ref 关键字")
            diagnosis_parts.append("• 确认结构体的 Drop trait 实现")
            diagnosis_parts.append("• 避免不必要的数据复制")
            
        else:
            diagnosis_parts.append("**通用错误排查步骤**：")
            diagnosis_parts.append("• **第一步**：仔细阅读错误信息，定位具体的错误行")
            diagnosis_parts.append("• **第二步**：检查该行及其上下文的语法正确性")
            diagnosis_parts.append("• **第三步**：确认所有依赖和导入是否正确")
            diagnosis_parts.append("• **第四步**：使用最小化代码重现问题")
            diagnosis_parts.append("• **第五步**：查阅官方文档或社区寻求帮助")
        
        # 如果有具体的错误信息
        if cairo_context.get("syntax_errors"):
            diagnosis_parts.append("\n**具体错误分析**：")
            for error in cairo_context["syntax_errors"][:2]:
                error_msg = error.get("message", "")
                if error_msg:
                    diagnosis_parts.append(f"• {error_msg}")
        
        return "\n".join(diagnosis_parts)
    
    def _generate_explanation_content(self, user_text: str) -> str:
        """生成解释性内容"""
        user_text_lower = user_text.lower()
        explanation_parts = []
        
        # 根据关键词提供相关解释
        if "felt" in user_text_lower:
            explanation_parts.append("**Felt 类型**：")
            explanation_parts.append("• Felt 是 Cairo 的基础数据类型，代表有限域元素")
            explanation_parts.append("• felt252 可以存储最大 252 位的整数")
            explanation_parts.append("• 适用于大多数数值计算和哈希操作")
            
        elif "storage" in user_text_lower:
            explanation_parts.append("**存储机制**：")
            explanation_parts.append("• Storage 结构定义合约的持久化状态")
            explanation_parts.append("• 使用 LegacyMap 实现键值对存储")
            explanation_parts.append("• 通过 read() 和 write() 方法访问存储")
            
        elif "trait" in user_text_lower:
            explanation_parts.append("**Trait 系统**：")
            explanation_parts.append("• Trait 定义了类型必须实现的方法集合")
            explanation_parts.append("• 类似于其他语言中的接口概念")
            explanation_parts.append("• 支持泛型和默认实现")
            
        elif "contract" in user_text_lower or "合约" in user_text_lower:
            explanation_parts.append("**智能合约基础**：")
            explanation_parts.append("• 使用 #[starknet::contract] 属性定义合约")
            explanation_parts.append("• Storage 结构存储合约状态")
            explanation_parts.append("• #[external(v0)] 定义公共接口函数")
            explanation_parts.append("• #[constructor] 定义合约初始化逻辑")
            
        else:
            explanation_parts.append("**Cairo 核心概念**：")
            explanation_parts.append("• **零知识友好**：Cairo 专为零知识证明设计")
            explanation_parts.append("• **类型安全**：强类型系统确保代码安全性")
            explanation_parts.append("• **函数式特性**：支持不可变数据和函数式编程")
            explanation_parts.append("• **StarkNet 集成**：原生支持 StarkNet 智能合约开发")
        
        return "\n".join(explanation_parts)
    
    def _generate_structured_fallback_content(self, user_intent: IntentType, 
                                            knowledge_items: List[Dict[str, Any]], 
                                            state: ChatState) -> str:
        """生成结构化的fallback内容"""
        user_text = state["messages"][-1]["content"] if state["messages"] else ""
        cairo_context = state.get("cairo_context", {})
        
        content_parts = []
        
        # 基于意图生成专业分析
        if user_intent == IntentType.QA:
            content_parts.append("基于 Cairo 语言的核心原理，这个问题涉及以下几个方面：")
            content_parts.append("• **语言特性**：Cairo 作为零知识证明友好的语言，具有独特的设计理念")
            content_parts.append("• **类型系统**：强类型系统确保代码安全性和可证明性")
            content_parts.append("• **最佳实践**：遵循 Cairo 编程规范可以提高代码质量")
            
        elif user_intent == IntentType.CODE_ANALYSIS:
            if cairo_context.get("has_code"):
                code_type = cairo_context.get("code_type", "代码")
                content_parts.append(f"对于这段 {code_type}，我基于 Cairo 编程最佳实践进行分析：")
                content_parts.append("• **结构分析**：代码的组织结构和模块化程度")
                content_parts.append("• **类型安全**：变量类型使用是否合理")
                content_parts.append("• **性能考虑**：是否遵循 Cairo 的性能优化原则")
            else:
                content_parts.append("代码分析需要具体的代码内容，建议提供完整的代码片段以便进行详细分析。")
                
        elif user_intent == IntentType.ERROR_DIAGNOSIS:
            content_parts.append("基于 Cairo 常见错误模式，我来分析可能的问题：")
            content_parts.append("• **编译错误**：语法错误、类型不匹配等编译时问题")
            content_parts.append("• **运行时错误**：数组越界、除零错误等运行时问题")
            content_parts.append("• **逻辑错误**：程序逻辑不符合预期的问题")
            
        elif user_intent == IntentType.CODE_GENERATION:
            content_parts.append("基于 Cairo 语法规范，我将为您提供代码示例：")
            content_parts.append("• **基础结构**：函数定义、变量声明等基本语法")
            content_parts.append("• **类型使用**：合适的数据类型选择")
            content_parts.append("• **错误处理**：适当的错误处理机制")
            
        else:
            content_parts.append("基于我对 Cairo 生态的理解，我来为您提供专业分析。")
        
        # 添加知识库状态说明
        if knowledge_items:
            content_parts.append(f"\n*注：虽然找到了 {len(knowledge_items)} 条相关信息，但相关性较低，以上分析主要基于 Cairo 通用原理。*")
        else:
            content_parts.append("\n*注：未找到直接相关的知识库内容，以上分析基于 Cairo 语言的通用原理和最佳实践。*")
        
        return "\n".join(content_parts)
    
    def _generate_intent_based_advice(self, user_intent: IntentType) -> str:
        """基于意图生成通用建议"""
        advice_map = {
            IntentType.QA: [
                "• 查阅 Cairo 官方文档获取最新信息",
                "• 通过实际编程练习加深理解",
                "• 关注 Cairo 社区的最新动态和最佳实践"
            ],
            IntentType.CODE_ANALYSIS: [
                "• 使用 Cairo 编译器检查代码语法",
                "• 遵循 Cairo 编码规范和风格指南",
                "• 考虑代码的可读性和可维护性"
            ],
            IntentType.ERROR_DIAGNOSIS: [
                "• 仔细阅读编译器错误信息",
                "• 使用调试工具逐步排查问题",
                "• 参考 Cairo 错误处理最佳实践"
            ],
            IntentType.CODE_GENERATION: [
                "• 先设计算法逻辑再编写代码",
                "• 注意 Cairo 的类型安全要求",
                "• 添加适当的注释和文档"
            ],
            IntentType.TUTORIAL: [
                "• 从基础概念开始循序渐进",
                "• 结合实际项目进行学习",
                "• 多参考官方示例和教程"
            ],
            IntentType.DEEP_RESEARCH: [
                "• 深入理解 Cairo 的设计原理",
                "• 关注零知识证明的相关理论",
                "• 参与 Cairo 社区讨论和贡献"
            ]
        }
        
        advice_list = advice_map.get(user_intent, advice_map[IntentType.QA])
        return "\n".join(advice_list)
    
    def _generate_learning_suggestions(self, user_intent: IntentType) -> str:
        """生成学习建议"""
        suggestions_map = {
            IntentType.QA: [
                "• [Cairo 官方文档](https://cairo-lang.org/docs/) - 权威学习资源",
                "• Cairo 语言基础教程和示例",
                "• Starknet 开发者社区和论坛"
            ],
            IntentType.CODE_ANALYSIS: [
                "• Cairo 代码审查最佳实践",
                "• 静态分析工具的使用",
                "• 代码质量评估标准"
            ],
            IntentType.ERROR_DIAGNOSIS: [
                "• Cairo 常见错误类型总结",
                "• 调试技巧和工具使用",
                "• 错误处理模式和最佳实践"
            ],
            IntentType.CODE_GENERATION: [
                "• Cairo 语法参考手册",
                "• 设计模式在 Cairo 中的应用",
                "• 代码生成工具和模板"
            ],
            IntentType.TUTORIAL: [
                "• Cairo 入门教程系列",
                "• 实战项目和案例分析",
                "• 在线编程练习平台"
            ],
            IntentType.DEEP_RESEARCH: [
                "• 零知识证明理论基础",
                "• Cairo 虚拟机原理",
                "• Starknet 架构深度解析"
            ]
        }
        
        suggestions = suggestions_map.get(user_intent, suggestions_map[IntentType.QA])
        return "\n".join(suggestions)


# 全局答案生成器实例
answer_generator = AdvancedAnswerGenerator()


def generate_answer(state: ChatState) -> ChatState:
    """生成增强的答案"""
    response_format = state.get("response_format", "structured")
    
    # 检查检索到的知识中是否包含代码
    has_code_in_knowledge = _check_code_in_knowledge(state.get("retrieved_knowledge", []))
    
    # 更新cairo_context中的has_code字段
    cairo_context = state.get("cairo_context", {})
    original_has_code = cairo_context.get("has_code", False)
    final_has_code = original_has_code or has_code_in_knowledge
    
    if cairo_context:
        cairo_context["has_code"] = final_has_code
        state["cairo_context"] = cairo_context
    
    # 检查是否应该使用LLM生成答案
    should_use_llm = _should_use_llm_for_answer(state)
    
    if should_use_llm:
        # 标记为需要LLM生成，不在这里生成答案
        state["use_llm_generation"] = True
        # 添加一个占位符消息，实际答案将由路由层的LLM生成
        state["messages"].append({
            "role": "assistant", 
            "content": "LLM_GENERATION_PLACEHOLDER",
            "metadata": {
                "intent": state.get("user_intent").value if state.get("user_intent") else "unknown",
                "confidence": state.get("confidence_score", 0),
                "has_code": final_has_code,
                "research_depth": state.get("research_depth", 0),
                "use_llm": True
            }
        })
    else:
        # 使用结构化响应
        if response_format == "structured":
            answer = answer_generator.generate_structured_response(state)
        else:
            answer = answer_generator.generate_simple_response(state)
        
        # 添加到消息历史
        state["messages"].append({
            "role": "assistant", 
            "content": answer,
            "metadata": {
                "intent": state.get("user_intent").value if state.get("user_intent") else "unknown",
                "confidence": state.get("confidence_score", 0),
                "has_code": final_has_code,
                "research_depth": state.get("research_depth", 0),
                "use_llm": False
            }
        })
    
    return state


def _should_use_llm_for_answer(state: ChatState) -> bool:
    """判断是否应该使用LLM生成答案"""
    # 获取用户意图
    user_intent = state.get("user_intent")
    
    # 对于通用问答，优先使用LLM
    if user_intent and user_intent.value in ["qa", "other"]:
        return True
    
    # 检查知识库质量
    knowledge_items = state.get("retrieved_knowledge", [])
    if not knowledge_items or len(knowledge_items) == 0:
        return True
    
    # 检查是否有高质量的知识内容
    user_text = ""
    if state.get("messages"):
        for msg in reversed(state["messages"]):
            if msg.get("role") == "user":
                user_text = msg.get("content", "")
                break
    
    # 使用现有的知识质量评估逻辑
    has_quality_knowledge = answer_generator._evaluate_knowledge_quality(knowledge_items, user_text)
    
    # 如果没有高质量知识，使用LLM
    if not has_quality_knowledge:
        return True
    
    return False


def _check_code_in_knowledge(knowledge_items: List[Dict[str, Any]]) -> bool:
    """检查检索到的知识中是否包含代码"""
    if not knowledge_items:
        return False
    
    # Cairo代码关键词
    cairo_keywords = [
        'fn ', 'struct ', 'trait ', 'impl ', 'mod ', 'use ',
        'let ', 'mut ', 'const ', 'static ', 'pub ',
        'contract', 'storage', 'event', 'interface',
        '#[derive', '#[contract', '#[storage', '#[event',
        'felt252', 'u256', 'u128', 'u64', 'u32', 'u16', 'u8',
        'Array', 'Span', 'ByteArray', 'ContractAddress',
        'transfer', 'approve', 'allowance', 'balance_of',
        'total_supply', 'mint', 'burn'
    ]
    
    # 检查每个知识项的内容
    for item in knowledge_items:
        content = item.get("content", "")
        if content:
            # 检查是否包含代码块标记
            if "```" in content:
                return True
            
            # 检查是否包含Cairo关键词
            content_lower = content.lower()
            for keyword in cairo_keywords:
                if keyword.lower() in content_lower:
                    return True
    
    return False
